<template>
    <div id="chart" ref="chartRef" :style="{ width: '480px', height: '145px' }"></div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

const chartRef = ref(null);
let chartInstance = null;

// 监听 ScalablePage 缩放的 scale 变化
const props = defineProps({
    scale: {
        type: Number,
        default: 1,
    },
});

const electricity2024Storage = localStorage.getItem('electricity2024');
const electricity2025Storage = localStorage.getItem('electricity2025');
const electricity2024 = ref(electricity2024Storage ? JSON.parse(electricity2024Storage) : [0.2571, 0.2576, 0.2567, 0.2545, 0.2545, 0.2562, 0.2593, 0.2584, 0.2788, 0.2583, 0.2652, 0.267]);
const electricity2025 = ref(electricity2025Storage ? JSON.parse(electricity2025Storage) : [0, 4.2803, 2.5448, 2.63, 2.57, 0, 0, 0, 0, 0, 0, 0]);
const PAC2024Storage = localStorage.getItem('PAC2024');
const PAC2025Storage = localStorage.getItem('PAC2025');
const PAC2024 = ref(PAC2024Storage ? JSON.parse(PAC2024Storage) : [64.09, 60.24, 63.34, 68.37, 59.34, 63.34, 82.36, 69.91, 30.13, 21.24, 69.49, 66.06]);
const PAC2025 = ref(PAC2025Storage ? JSON.parse(PAC2025Storage) : [0, 0, 1.538, 1.84, 10.9, 0, 0, 0, 0, 0, 0, 0]);

// 初始化 Echarts 图表
const initChart = () => {
    if (!chartRef.value) return;

    // 重新初始化 chart，处理高 DPI
    chartInstance = echarts.init(chartRef.value, null, {
        devicePixelRatio: window.devicePixelRatio * props.scale || 1,
    });

    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line',
            },
        },
        legend: {
            data: ['2024水厂用电能耗', '2025水厂用电能耗', '2024PAC单耗', '2025PAC单耗'],
            textStyle: {
                color: '#ccc',
                fontSize: '8px',
            },
            itemWidth: 8, // 控制圆点宽度
            itemHeight: 8, // 控制圆点高度
            icon: 'circle', // 确保圆点为实心圆
        },
        grid: {
            left: '0%',
            top: 30,
            right: '3%',
            bottom: '0%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            boundaryGap: false, // 让折线贴合 x 轴
            data: [
                '1月',
                '2月',
                '3月',
                '4月',
                '5月',
                '6月',
                '7月',
                '8月',
                '9月',
                '10月',
                '11月',
                '12月',
            ],
            axisLabel: {
                color: '#fff',
                fontSize: '8px',
            },
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                color: '#fff',
                fontSize: '8px',
            },
            splitLine: {
                lineStyle: {
                    type: 'dashed', // 修改背景线为虚线
                    color: '#444', // 线条颜色
                    width: 0.3,
                    dashOffset: 5, // 控制虚线间距
                },
            },
        },
        series: [
            {
                name: '2024水厂用电能耗',
                type: 'line',
                smooth: false, // 取消平滑，变为直线
                data: electricity2024.value,
                itemStyle: {
                    color: '#ff9300',
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(255,147,0,0.5)' },
                        { offset: 0.6, color: 'rgba(255,147,0,0.1)' },
                        { offset: 1, color: 'rgba(255,147,0,0)' },

                    ]),
                },
                symbol: 'circle', // 设置为实心圆
                symbolSize: 7, // 圆点大小
                lineStyle: {
                    width: 0.5, // 线条宽度
                },
            },
            {
                name: '2025水厂用电能耗',
                type: 'line',
                smooth: false, // 取消平滑
                data: electricity2025.value,
                itemStyle: {
                    color: '#3BB7FF',
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(59, 183, 255, 0.5)' },
                        { offset: 0.6, color: 'rgba(59, 183, 255, 0.1)' },
                        { offset: 1, color: 'rgba(59, 183, 255, 0)' },
                    ]),
                },
                symbol: 'circle', // 设置为实心圆
                symbolSize: 7, // 圆点大小
                lineStyle: {
                    width: 0.5, // 线条宽度
                },
            },
            {
                name: '2024PAC单耗',
                type: 'line',
                smooth: false, // 取消平滑
                data: PAC2024.value,
                itemStyle: {
                    color: '#00E5A0',
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(52, 226, 226, 0.5)' },
                        { offset: 0.6, color: 'rgba(52, 226, 226, 0.1)' },
                        { offset: 1, color: 'rgba(52, 226, 226, 0)' },
                    ]),
                },
                symbol: 'circle', // 设置为实心圆
                symbolSize: 7, // 圆点大小
                lineStyle: {
                    width: 0.5, // 线条宽度
                },
            },
            {
                name: '2025PAC单耗',
                type: 'line',
                smooth: false,
                data: PAC2025.value,
                itemStyle: {
                    color: '#45D3F5',
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(69, 211, 245, 0.5)' },
                        { offset: 0.6, color: 'rgba(69, 211, 245, 0.1)' },
                        { offset: 1, color: 'rgba(69, 211, 245, 0)' },
                    ]),
                },
                symbol: 'circle', // 设置为实心圆
                symbolSize: 7, // 圆点大小
                lineStyle: {
                    width: 0.5, // 线条宽度
                },
            },
        ],
    };

    chartInstance.setOption(option);
};

// 监听 ScalablePage 的缩放比例变化
watch(
    () => props.scale,
    (newScale) => {
        if (chartInstance) {
            nextTick(() => {
                chartInstance.dispose();
                initChart();
            });
        }
    }
);

onMounted(async () => {
    await initChart();
    await getElectricityConsumption()
    window.addEventListener('resize', resizeChart);
});

// 窗口变化时重新 resize
const resizeChart = () => {
    if (chartInstance) {
        chartInstance.resize();
    }
};

watch([electricity2024, electricity2025, PAC2024, PAC2025], () => {
    if (chartInstance) {
        chartInstance.setOption({
            series: [
                { data: electricity2024.value },
                { data: electricity2025.value },
                { data: PAC2024.value },
                { data: PAC2025.value },
            ]
        });
        localStorage.setItem('electricity2024', JSON.stringify(electricity2024.value));
        localStorage.setItem('electricity2025', JSON.stringify(electricity2025.value));
        localStorage.setItem('PAC2024', JSON.stringify(PAC2024.value));
        localStorage.setItem('PAC2025', JSON.stringify(PAC2025.value));
    }
}, { deep: true });


/**
 * 获取 2023年水厂用电能耗
 */
async function getElectricityConsumption() {
    /**
 * 获取2024年能耗数据
 * @param year 年份
 */
    async function dataList2024(year) {
        await fetch(`http://192.168.254.34:8090/getRealtimeData/selectHistoryIndicator?queryDate=2024`)
            .then((r) => {
                if (r.status === 200) {
                    return r.json();
                } else {
                    return Promise.reject(r.json());
                }
            })
            .then((res) => {
                const data = res.data
                electricity2024.value = getMonthlyDataKey('月用电单耗', data, '2024');
                PAC2024.value = getMonthlyDataKey('PAC月耗', data, '2024');
            });
    }

    /**
     * 获取2025年能耗数据
     * @param year 年份
     */
    async function dataList2025(year) {
        await fetch(`http://192.168.254.34:8090/getRealtimeData/selectHistoryIndicator?queryDate=2025`)
            .then((r) => {
                if (r.status === 200) {
                    return r.json();
                } else {
                    return Promise.reject(r.json());
                }
            })
            .then((res) => {
                const data = res.data
                electricity2025.value = getMonthlyDataKey('月用电单耗', data, '2025');
                PAC2025.value = getMonthlyDataKey('PAC月耗', data, '2025');
            });
    }
    await dataList2024('2024')
    await dataList2025('2025')
}

function getMonthlyDataKey(keyword, data, currentYear) {
    // 获取当前年份
    // const currentYear = new Date().getFullYear();

    // 初始化结果数组，默认值为0
    const result = new Array(12).fill(0);

    // 遍历12个月，查找对应的数据
    for (let month = 1; month <= 12; month++) {
        const monthStr = month.toString().padStart(2, '0');
        const searchKey = `${currentYear}-${monthStr}-${keyword}`;
        // 在data中查找匹配的项
        const foundItem = data.find(item => item.key === searchKey);
        if (foundItem) {
            // 将字符串转换为数字（如果可以）
            result[month - 1] = isNaN(foundItem.value) ? foundItem.value : parseFloat(foundItem.value);
        }
    }

    return result;
}
</script>

<style scoped>
#chart {
    width: 480px;
    height: 145px;
}
</style>